package com.dxq.test.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.SPUtils;
import com.dxq.test.App;
import com.dxq.test.activity.LivestockActivity;
import com.dxq.test.common.Constant;
import com.dxq.test.R;
import com.dxq.test.activity.LabelAddActivity;
import com.dxq.test.activity.MainActivity;
import com.dxq.test.activity.PastureActivity;
import com.dxq.test.activity.ScanQRCodeActivity;
import com.dxq.test.db.Label;
import com.dxq.test.db.Pasture;
import com.j256.ormlite.dao.ForeignCollection;

import java.util.ArrayList;
import java.util.List;


public class Fragment1_Pasture extends Fragment implements View.OnClickListener {

    private static final int REQUEST_CODE_SCAN = 100;
    private static final int REQUEST_CODE_OF_SCAN_PAGE = 111;
    private View view;// this fragment UI
    private ImageView ivBack;
    private TextView tvTitle;

    private String[] types = {"牛", "羊", "禽类"};
    private int[] ivTypes = {R.drawable.cow, R.drawable.sheep, R.drawable.chicken};
    private EditText etSerialNumber, etName, etWeight;
    private Button btnScan, btnChangePasture, btnChangeType, btnAdd;
    private TextView tvType, tvPastureName, tvBatteryLevel, tvTemperature, tvExerciseSteps;
    private ImageView ivType;
    private TextView tvCL, tvDB,tvChuLan, tvYiTao;
    private LinearLayout llCL, llDB, llChuLan, llYiTao;
    private RadioGroup rgSex, rgBreedingStatus;
    private RadioButton rbg, rbm, rbb1, rbb2, rbb3;
    private Spinner spPasture;

    private String sex = "";
    private String breedingStatus = "";
    private String QRCodeID = "";
    private int type;

    private List<Label> selectTypeLabel = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_pasture, null);
        initView();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //隐藏时所作的事情
        } else {
            //显示时所作的事情
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        tvPastureName.setText(App.select_pasture_name);
        tvType.setText("养殖品种：" + types[App.select_label_type]);
        ivType.setImageResource(ivTypes[App.select_label_type]);
        getData();
    }

    private void initView() {
        ivBack = view.findViewById(R.id.ivBack);
        tvTitle = view.findViewById(R.id.tvTitle);
        ivBack.setVisibility(View.GONE);
        tvTitle.setText("分群计数");
        tvPastureName = view.findViewById(R.id.tvPastureName);
        tvType = view.findViewById(R.id.tvType);
        ivType = view.findViewById(R.id.ivType);
        tvCL = view.findViewById(R.id.tvCL);
        tvDB = view.findViewById(R.id.tvDB);
        tvChuLan = view.findViewById(R.id.tvChuLan);
        tvYiTao = view.findViewById(R.id.tvYiTao);
        llCL = view.findViewById(R.id.llCL);
        llDB = view.findViewById(R.id.llDB);
        llChuLan = view.findViewById(R.id.llChuLan);
        llYiTao = view.findViewById(R.id.llYiTao);
        spPasture = view.findViewById(R.id.spPasture);
        btnScan = view.findViewById(R.id.btnScan);
        btnChangePasture = view.findViewById(R.id.btnChangePasture);
        btnChangeType = view.findViewById(R.id.btnChangeType);
        btnAdd = view.findViewById(R.id.btnSubmit);

        //tvType.setOnClickListener(this);
        btnScan.setOnClickListener(this);
        btnChangePasture.setOnClickListener(this);
        btnChangeType.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        llDB.setOnClickListener(this);
        llCL.setOnClickListener(this);
        llChuLan.setOnClickListener(this);
        llYiTao.setOnClickListener(this);


//        // 声明一个ArrayAdapter用于存放简单数据
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//                getActivity(), android.R.layout.simple_dropdown_item_1line,
//                getPastureData());
//        // 把定义好的Adapter设定到spinner中
//        spPasture.setAdapter(adapter);
//        // 为第一个Spinner设定选中事件
//        spPasture.setSelection(0);
//        getPastureByName(getPastureData().get(0));
//        spPasture.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view,
//                                       int position, long id) {
//                //在选中之后触发
//                getPastureByName(getPastureData().get(position));
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                // 这个一直没有触发，我也不知道什么时候被触发。
//                //在官方的文档上说明，为back的时候触发，但是无效，可能需要特定的场景
//            }
//        });
    }

//    private int getPastureByName(String name) {
//        List<Pasture> pastures = ((MainActivity) getActivity()).tablesDao.queryPastureByName(name);
//        if (pastures != null && pastures.size() > 0) {
//            for (Pasture pasture : pastures) {
//                if (pasture.getName().equals(name)) {
//                    //缓存牧场id
//                    SPUtils.getInstance().put(App.pasture_id, pasture.getPasture_id());
//                    ToastUtils.showShort(SPUtils.getInstance().getInt(App.pasture_id) + "");
//                    return pasture.getPasture_id();
//                }
//            }
//        }
//        return 0;
//    }

    private void getData() {
        selectTypeLabel.clear();
        Pasture pasture = ((MainActivity) getActivity()).tablesDao.queryPastureById(App.select_pasture_id);
        if (null != pasture) {
            ForeignCollection<Label> labels = pasture.getLabels();
            for (Label label : labels) {
                selectTypeLabel.add(label);
            }
        }
        //显示牲畜详情
        int size1 = 0, size2 = 0, size3 = 0, size4 = 0;
        //存栏,打标:根据serialNumber是否为空判断
        int clSize = selectTypeLabel.size();
        for (Label label : selectTypeLabel) {
            if (label.getBreedingStatus().equals(Constant.BREEDSTATUS_CUNLAN)) {
                //存栏
                size1++;
            }
            if (!label.getSerialNumber().equals("")) {
                //打标
                size2++;
            }
            if (label.getBreedingStatus().equals(Constant.BREEDSTATUS_CHULAN)) {
                //出栏
                size3++;
            }
            if (label.getBreedingStatus().equals(Constant.BREEDSTATUS_SIWANG)) {
                //死亡
                size4++;
            }
        }
        tvCL.setText(String.valueOf(size1));//存栏数量
        tvDB.setText(String.valueOf(size2));//打标数量
        tvChuLan.setText(String.valueOf(size3));//出栏数量
        tvYiTao.setText(String.valueOf(size4));//异淘数量
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btnChangeType:
                typeDialog(tvType.getText().toString());
                break;

            case R.id.btnScan:
                startActivity(new Intent(getActivity(), ScanQRCodeActivity.class));
                break;

            case R.id.btnChangePasture:
                startActivity(new Intent(getActivity(), PastureActivity.class));
                break;

            case R.id.btnSubmit:
                startActivity(new Intent(getActivity(), LabelAddActivity.class));
                break;

            case R.id.llCL:
                intent = new Intent(getActivity(), LivestockActivity.class);
                intent.putExtra("breedingStatus", Constant.BREEDSTATUS_CUNLAN);
                startActivity(intent);
                break;

            case R.id.llDB:
                intent = new Intent(getActivity(), LivestockActivity.class);
                intent.putExtra("breedingStatus", Constant.BREEDSTATUS_CUNLAN);
                intent.putExtra("serialNumber", true);
                startActivity(intent);
                break;

            case R.id.llChuLan:
                intent = new Intent(getActivity(), LivestockActivity.class);
                intent.putExtra("breedingStatus", Constant.BREEDSTATUS_CHULAN);
                startActivity(intent);
                break;

            case R.id.llYiTao:
                intent = new Intent(getActivity(), LivestockActivity.class);
                intent.putExtra("breedingStatus", Constant.BREEDSTATUS_SIWANG);
                startActivity(intent);
                break;
        }
    }

    private List<String> getPastureData() {
        List<String> list = new ArrayList<>();
        List<Pasture> pastures = ((MainActivity) getActivity()).tablesDao.queryPastureAll();
        if (null != pastures && pastures.size() > 0) {
            for (Pasture pasture : pastures) {
                list.add(pasture.getName());
            }
        }
        return list;
    }

    String typeName = "";
    int finalPosition = 0;

    private void typeDialog(String type) {
        int position = 0;
        for (int i = 0; i < types.length; i++) {
            if (type.contains(types[i])) {
                position = i;
                break;
            }
        }
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("选择牲畜")//设置对话框的标题
                .setSingleChoiceItems(types, position, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        typeName = types[which];
                        finalPosition = which;
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        tvType.setText("当前牲畜：" + typeName);
                        SPUtils.getInstance().put(Constant.LABEL_TYPE, finalPosition, true);
                        App.select_label_type = finalPosition;
                        Toast.makeText(getActivity(), typeName, Toast.LENGTH_SHORT).show();
                        getData();
                    }
                }).create();
        dialog.show();
    }


}
